<template>
  <component
    :is="whichPopupType"
    position="bottom"
    closeable
    v-model:show="show"
    v-model:visible="show"
    v-model:title="dialogConfig.title"
    :width="dialogConfig.width"
    :headerFixed="dialogConfig.headerFixed"
    :auto-height="true"
  >
    <div class="dialog-play-box">
      <h4 class="dialog-play-box__title">
        <em>{{ t("thirdGame.thirdGame_01") }}</em>
        <span v-for="item in defaultCurrency" @click="changeDefaultCurrency(item)" :class="{'active': currentChoiseCurrency.currencyId === item.currencyId}" :key="item.currencyIds">
          <img :src="item.currencyIcon" alt="">{{ item.currencyName }}
        </span>
      </h4>
      <ul class="dialog-play-box__list">
        <li v-for="item in currentOptionalCurrency" :key="item.id">
          <div class="dialog-play-box__currency">
            <img :src="item.currencyIcon" alt="">{{item.currencyName}}
          </div>
          <div class="dialog-play-box__right">
            <div class="dialog-play-box__swaprate">
              <div class="amount">{{item.totalCoin}} {{currentChoiseCurrency.currencyName}}</div>
              <div class="rateInfo">1{{item.currencyName}} ≈ {{item.rate}} {{currentChoiseCurrency.currencyName}} </div>
            </div>
            <div class="dialog-play-box__action" @click="handleWallet(item)" v-if="item.totalCoin < 1">{{t("thirdGame.thirdGame_02")}}</div>
            <div class="dialog-play-box__action" @click="handleSwap(item)" v-else>{{t("thirdGame.enter")}}</div>
          </div>
        </li>
      </ul>
    </div>
  </component>
</template>

<script setup lang="ts" name="CurrencyExchange">
import userinfo from '@/store/userinfo';
import system from '@/store/system';
import gamesApi from '@/api/modules/games';
import nocache from '@/store/nocache';

const piniaUserinfo:any = userinfo();
const piniaSystem:any = system();
const emits = defineEmits(['queryThirdUrl', 'update:visible']);
const { t } = useI18n();

// 当前钱包
const currentWallet = computed(()=> piniaUserinfo.getCurrentWallet);

const whichPopupType = computed(()=>{
  return piniaSystem.getIsH5 ?
    markRaw(defineAsyncComponent(() => import('vant/es/popup'))) :
    markRaw(defineAsyncComponent(() => import('@/components/Dialog/index.vue')));
});

const props = defineProps({
  playId: {
    type: [Number, String],
    default: ""
  },
  visible: {
    type: Boolean,
    default: false
  }
})

const data:any = reactive({
  dialogConfig: {
    title: computed(()=> t("UserInfo.BCSwap")),
    width: 450,
    headerFixed: false,
  },
  show: props.visible,
  defaultCurrency: [],
  optionalCurrency: [],
  currentOptionalCurrency: [],
  currentChoiseCurrency: {}
});

const {
  dialogConfig,
  defaultCurrency,
  optionalCurrency,
  currentOptionalCurrency,
  currentChoiseCurrency,
  show,
} = toRefs(data);

watch(
  () => props.visible,
  (val, preVal) => {
    show.value = val;
    // show.value = currentOptionalCurrency.value.length > 0 && val;
  },
  { immediate: false, deep: true },
);

watch(
  () => show.value,
  (val, preVal) => {
    if(!val){
      emits('update:visible', val);
    }
  },
  { immediate: false, deep: true },
);

const getGameRateList = () => {
  gamesApi.getGameRateList({
    playId: props.playId,
    currencyId: piniaUserinfo.getCurrentWallet.currencyId,
  }).then((response: any) => {
    console.log("货币兑换============================", response)
    if(response.code === 200){
      optionalCurrency.value = response.data.list || [];
      defaultCurrency.value = (response.data.currencyIds.split(",") || []).map((element:any) => {
        return piniaUserinfo.getWallet.find((im:any) => im.currencyId == element);
      });
      currentChoiseCurrency.value = defaultCurrency.value[0];
      conversion();
    }
  })
}
getGameRateList();

// 选择默认币种
const changeDefaultCurrency = (item:any) => {
  currentChoiseCurrency.value = item;
  conversion();
}

// 选择默认币种后换算
const conversion = () => {
  optionalCurrency.value = optionalCurrency.value.map((element:any)=>{
    const wallet = piniaUserinfo.getWallet.find((im:any) => im.currencyId == element.currencyId);
    element.totalCoin = (element.rate * wallet.money).toFixed(6);
    element.currencyIcon = wallet.currencyIcon;
    element.currencyName = wallet.currencyName;
    return element;
  });
  currentOptionalCurrency.value = optionalCurrency.value.filter((element:any)=>element.targetCurrencyId === currentChoiseCurrency.value.currencyId);
}

// 兑换
const handleWallet = (item: any) => {

}

// 进入
const handleSwap = (item: any) => {
  // 修改当前的钱包
  console.log("兑换目标的数据", item);
  const targetWallet: any = piniaUserinfo.getWallet.find((im:any) => im.currencyId == item.targetCurrencyId);
  if(targetWallet){
    piniaUserinfo.setCurrentWallet(targetWallet);
    gamesApi.findGameInRate({ rateId: item.rateId }).then((response:any) => {
      if (response.code == 200) {
        show.value = false;
        emits('queryThirdUrl');
      }
    })
  }
}

</script>

<style lang="scss" scoped>
@import url('./index.scss');
</style>
